local NULL = ngx.null

local _M = {}

do
  function _M.coalesce(...)
    local arg = {...}
    if arg then
      if type(arg) == "table" and next(arg) then
        for i = 1, #arg do
          if arg[i] and arg[i] ~= NULL then
            return arg[i]
          end
        end
      end
    end
    return nil
  end


  -- boolean
  do
    function _M.to_yes_no(v)
      if v then
        return "yes"
      end
      return "no"
    end
  end


  -- string
  do
    function _M.string_start_with(s, prefix)
      return string.sub(s, 1, string.len(prefix)) == prefix
    end

    function _M.is_nil_or_empty_string(v)
      return (not v) or (v == "")
    end
  end


    -- table
  do
    function _M.normalize_field_value_args(args, fields)
      if type(args) ~= "table" then
        return
      end

      local result = {}
      if #args > 0 then
        for i = 1, #args, 2 do
          local k, v = args[i], args[i+1]
          if v then
            result[#result+1] = k
            result[#result+1] = v
          end
        end
      else
        if fields  and  type(fields) == "table"  then
          for i = 1, #fields do
            local k = fields[i]
            local v = args[k]
            if v then
              result[#result+1] = k
              result[#result+1] = v
            end
          end
        else
          for k, v in pairs(args) do
            if v then
              result[#result+1] = k
              result[#result+1] = v
            end
          end
        end
      end
      return result
    end


    function _M.merge_table(...)
      local argv   = {...}

      if #argv == 0 then
        return nil
      end
      if #argv == 1 then
        return argv[1]
      end

      local result = { unpack(argv[1]) }
      for i = 2, #argv do
        local array = argv[i]
        if type(array)=="table" then
          for ii = 1, #array do
            result[#result+1] = array[ii]
          end
        end
      end
      return result
    end
  end
end
return _M
